// pages/member/addressAdd_v2/addressAdd_v2.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowStreet: false,
    form: {
      username: "",
      mobile: "",
      province: "",
      city: "",
      district: "",
      streetName: "",
      address: "",
      isDefault: false,
      country_code: '86'
    },
    country_code: 0,
    addressName: "",
    openDateLw: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    districtVal: [],
    opren: true,
    acr: true,
    is_region: 0,
    address_parse_open:0,
    address_parse_show:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //加载地址数据初始化
    this._initAddressInfo();
    this.getIsOpenAddress();
    if(options.isdefault){
      this.setData({
        "form.isDefault":options.isdefault == 'true'?true:false
      })
    }
    let yz_basic_info = wx.getStorageSync("yz_basic_info");
    this.setData({
      address_parse_open:yz_basic_info.plugin_setting.address_parse_open?yz_basic_info.plugin_setting.address_parse_open:0,
      country_code: yz_basic_info.home.system.country_code||false
    })
  },
  streetClose(e) {
    this.setData({
      streetShow: false,
      opren: true,
    });
  },
  onTransitionEnd(e) {
    console.log(e);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  tapToParse(){
    this.setData({
      address_parse_show:true
    })
  },
  toPostMethod(e){
    let einfo = e.detail;
    this.setData({
      "form.address":einfo.address,
      "form.province":einfo.province,
      "form.city":einfo.city,
      "form.district":einfo.region,
      "form.username":einfo.name,
      "form.mobile":einfo.mobile,
    })
    this._getStreet(einfo.region_id,einfo.street);
    this.setData({
      addressName:`${einfo.province}${einfo.city}${einfo.region}`
    })
    this.address_parseClose();
  },
  address_parseClose(){
    this.setData({
      address_parse_show:false
    })
  },
  getIsOpenAddress() {
    var that = this;
    let urlStr = app.getNetAddresss("member.member-address.is-region");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          that.setData({
            is_region: res.data.is_region,
          });
        } else {
          console.log(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //获取街道
  _getStreet(param,key='') {
    var that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              isShowStreet: true,
            });
            if(key){
              that.setData({
                'form.streetName':key
              })
            }
          } else {
            that.setData({
              isShowStreet: false,
            });
          }
        } else {
          that.setData({
            isShowStreet: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  countryCodeInput: function (e) {
    let value = e.detail.value;
    this.setData({
      "form.country_code": value,
    });
  },
  //默认地址开关值绑定
  isDefaultChange: function (e) {
    let isDefault = e.detail;
    this.setData({
      "form.isDefault": isDefault,
    });
  },
  //收件人输入绑定
  usernameinp: function (e) {
    let nameval = e.detail.value;
    this.setData({
      "form.username": nameval,
    });
  },
  //联系电话输入绑定
  mobileinp: function (e) {
    let mobileval = e.detail.value;
    this.setData({
      "form.mobile": mobileval,
    });
  },
  //详细地址绑定输入
  addressinp: function (e) {
    let addressval = e.detail.value;
    console.log(addressval);
    this.setData({
      "form.address": addressval,
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      openDateLw: false,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },
  //打开地址选择器
  openDateLwtbtn: function () {
    this.setData({
      openDateLw: true,
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  // 确定选择收货地址
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      "form.streetName": "",
      districtVal: "",
      addressName:
        seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
      "form.province": seleData[0].name,
      "form.city": seleData[1].name,
      "form.district": seleData[2].name,
    });
    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  streetChoose() {
    if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: "none",
        title: "请先选择所在地区",
        duration: 1500,
      });
    } else {
      this.setData({
        streetShow: true,
        opren: false,
      });
    }
  },
  //选择街道
  streetConfirm(e) {
    let strname = e.target.dataset.strname;
    this.setData({
      "form.streetName": strname,
      streetShow: false,
    });
  },
  appendAddress() {
    let urlStr = "";
    if (app._isTextEmpty(this.data.form.country_code) && this.data.country_code) {
      wx.showToast({
        icon: "none",
        title: "请输入区号",
        duration: 1500,
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.username)) {
      wx.showToast({
        icon: "none",
        title: "请输入收货人姓名",
        duration: 1500,
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请输入手机机号",
        duration: 1500,
      });
      return;
    }
    if (app._isMoblie(this.data.form.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请输入正确的手机号",
        duration: 1500,
      });
      return;
    }
    if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: "none",
        title: "请选择所在区域",
        duration: 1500,
      });
      return;
    }

    // if (
    //   this.data.is_region == 1 &&
    //   this.data.isShowStreet &&
    //   app._isTextEmpty(this.data.form.streetName)
    // ) {
    //   wx.showToast({
    //     icon: "none",
    //     title: "请选择所在街道",
    //     duration: 1500,
    //   });
    //   return;
    // }

    if (app._isTextEmpty(this.data.form.address)) {
      wx.showToast({
        icon: "none",
        title: "请输入详细地址",
        duration: 1500,
      });
      return;
    }
    let json = {};
    json = {
      address_id: this.data.form.address_id,
      username: this.data.form.username,
      mobile: this.data.form.mobile,
      city: this.data.form.city,
      address: this.data.form.address,
      province: this.data.form.province,
      isdefault: this.data.form.isDefault ? 1 : 0,
      district: this.data.form.district,
      street: this.data.form.streetName,
    };
    if(this.data.country_code) json.country_code =  this.data.form.country_code;

    urlStr = app.getNetAddresss("member.member-address.store");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500); //延迟时间
            },
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
});
